/**
 * This file is part of Wireless TransFer.
 *
 *   Wireless TransFer is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *	
 *   Wireless TransFer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Wireless TransFer.  If not, see <http://www.gnu.org/licenses/>.
 *	 
 *	 Copyright (C) 2011
 *   @author christofferP
 */
package com.wirelesstransfer.server.WIFI.handlers;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import android.util.Log;

import com.wirelesstransfer.connection.ServerActions;
import com.wirelesstransfer.server.Ifiles;
import com.wirelesstransfer.server.ServerConnection;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClientsHandler;
import com.wirelesstransfer.server.authentication.Code;

/**
 * ConnectHandler generates a session for a authenticated client
 * 
 * 
 * Headers needed:
 * authCode
 * 
 * @author christofferP
 *
 */

public class ConnectHandler extends AbstractHandler {
	
	private String TAG = "ConnectHandler";
	
	private int authCode;
	private int connectionCode;
	private String sessionId;
	
	private Ifiles files;
	
	public ConnectHandler(Ifiles files){
		this.files = files;
	}
	
	public void handle(String target,
			Request baseRequest,
			HttpServletRequest request,
			HttpServletResponse response) 
	throws IOException, ServletException {
		Log.v(TAG, "Handling request");

		baseRequest.setHandled(true);

		//Get autheticate code from client and server
		authCode = Integer.parseInt(request.getHeader(ServerActions.AUTHCODE));
		connectionCode = ServerConnection.getInstance().getCode();
		Log.v(TAG, "ClientCode: " + authCode + " ServerCode: " + connectionCode);
		

 		if(Code.validCode(authCode)){
			Log.v(TAG, "Code OK");
 			
 			sessionId = ConnectedClientsHandler.getInstance().generateId();
 			
 			response.setHeader(ServerActions.SESSIONID, sessionId);
 			response.setHeader(ServerActions.FILES, files.toString());
 			response.setStatus(HttpServletResponse.SC_OK);
 		}
		else {
			Log.v(TAG, "Code NOT OK");
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			response.addHeader(ServerActions.MESSAGE, "invalid authCode");

		}		
	}
}
